<template>
  <view>
    <!--    补卡-->
    <HeaderNavTabarSvg :title="title">
      <image class="bukaSvg" src="/static/icon/auditSVG/buka.svg" @tap="goHistoryView"></image>
    </HeaderNavTabarSvg>

    <view class="picker-content" @tap="toggle">
      <view class="measurement-info-list">
        <text class="info-list-left isrequired">补卡日期</text>
        <view class="info-list-right">
          <view class="uni-input">{{ bukaData.datetimeValue ? bukaData.datetimeValue : '请选择' }}</view>
          <i class="iconfont icon-youjiantou"></i>
        </view>
      </view>
    </view>
    <uv-datetime-picker
      ref="datetimePicker"
      v-model="time"
      :formatter="formatter"
      mode="date"
      :maxDate="dayjs().valueOf()"
      @confirm="confirm"
    >
    </uv-datetime-picker>
    <view class="picker-content">
      <view
        :class="{ bukabanci: bukaData.datetimeValue === '' }"
        class="measurement-info-list"
      >
        <text class="info-list-left isrequired">补卡班次</text>
        <view class="info-list-right" @tap="openPicker">
          <view class="uni-input"> {{ bukaData.bukabanci ? bukaData.bukabanci : '请选择' }}</view>
          <i class="iconfont icon-youjiantou"></i>
        </view>
      </view>
    </view>
    <view class="picker-content" @tap="togglebuka">
      <view v-if="bukaData.bukabanci !== ''" class="measurement-info-list">
        <text class="info-list-left isrequired">补卡时间</text>
        <view class="info-list-right">
          <view class="uni-input">{{ bukaData.bukashijian ? bukaData.bukashijian : '请选择' }}</view>
          <i class="iconfont icon-youjiantou"></i>
        </view>
      </view>
    </view>
    <uv-picker
      ref="picker"
      :columns="columns"
      @confirm="confirm1"
      :defaultIndex="pickerDefaultTime"
    ></uv-picker>
    <view class="textarea-box">
      <text class="info-list-left isrequired">补卡事由</text>
      <textarea v-model="bukaData.bakahsiyou" class="textinfo-list" placeholder="请输入"></textarea>
    </view>
    <uni-popup ref="popup" append-to-body="true" background-color="#fff">
      <view class="popup-content">
        <view class="header-box">
          <p>请选择班次</p>
          <view class="module-image-ba" @tap="closePop">
            <image src="@/static/icon/close.svg"></image>
          </view>
        </view>
        <view class="card-list">
          <view
            v-for="(item, index) in listTime"
            :key="index"
            class="list"
            @tap="optionHistory(item)"
          >
            <h4>
              <text
                >{{ item.punchType }}
                <text v-show="item.punchTime"
                  >({{ new dayjs(item.punchTime).format('HH:mm:ss') }})
                </text>
              </text>
              <text :class="item.type" style="margin-left: 20rpx">{{ item.type }}</text>
            </h4>

            <p v-show="item.punchType === '上午上班'">应08:00上班</p>
            <p v-show="item.punchType === '上午下班'">应12:00下班</p>
            <p v-show="item.punchType === '下午上班'">应14:00上班</p>
            <p v-show="item.punchType === '下午下班'">应18:00下班</p>
          </view>
        </view>
      </view>
    </uni-popup>
    <!--    说明附件-->
    <DescriptionAttachment @getDesignDrawingsEmit="getDesignDrawingsEmit" />
    <!--    审批流程-->
    <AuditApplicationSteps :ruleId="'buka'" />
    <!--    底部占位符-->
    <view class="blank"></view>
    <!--    保存-->
    <view class="buttonContainer">
      <button class="buttonClass" @click="clickSave">提交</button>
    </view>
  </view>
</template>

<script setup>
import HeaderNavTabarSvg from '@/components/HeaderNavTabarSvg/HeaderNavTabar.vue'
import { onLoad } from '@dcloudio/uni-app'
import { attendanceApplyApi, getAttendanceRecordList } from '@/api/attendance'
import AuditApplicationSteps from '@/components/audit/function/auditApplicationSteps.vue'
import DescriptionAttachment from '@/components/audit/function/descriptionAttachment.vue'
import { ref, watch } from 'vue'
import dayjs from 'dayjs'
import { getUserProfile } from '@/api/system/user'
import approvalProcessState from '@/store/modules/approvalProcess'
import { isObjectValuesNotEmpty } from '@/utils/objIsnull.js'
const title = '补卡'
const goHistoryView = () => {
  uni.navigateTo({
    url: '/components/TypeDefineModel?type=补卡',
  })
}
const popup = ref(null)
const datetimePicker = ref(null)
const picker = ref(null)
let time = dayjs()
const listTime = ref([])

let bukaData = ref({
  datetimeValue: '',
  bukabanci: '',
  bukashijian: '',
  bakahsiyou: '',
})
const pickerDefaultTime = ref([['2018-05-12'], ['00'], ['00']])
const columns = ref([
  [bukaData.value.datetimeValue],
  [
    '00',
    '01',
    '02',
    '03',
    '04',
    '05',
    '06',
    '07',
    '08',
    '09',
    '10',
    '11',
    '12',
    '13',
    '14',
    '15',
    '16',
    '17',
    '18',
    '19',
    '20',
    '21',
    '22',
    '23',
  ],
  [
    '00',
    '01',
    '02',
    '03',
    '04',
    '05',
    '06',
    '07',
    '08',
    '09',
    '10',
    '11',
    '12',
    '13',
    '14',
    '15',
    '16',
    '17',
    '18',
    '19',
    '20',
    '21',
    '22',
    '23',
    '24',
    '25',
    '26',
    '27',
    '28',
    '29',
    '30',
    '31',
    '32',
    '33',
    '34',
    '35',
    '36',
    '37',
    '38',
    '39',
    '40',
    '41',
    '42',
    '43',
    '44',
    '45',
    '46',
    '47',
    '48',
    '49',
    '50',
    '51',
    '52',
    '53',
    '54',
    '55',
    '56',
    '57',
    '58',
    '59',
  ],
])
// 打开选择器
const toggle = (type) => {
  datetimePicker.value.open()
}
const togglebuka = (type) => {
  picker.value.open()
}
const closePop = () => {
  popup.value.close()
}
const openPicker = () => {
  if (bukaData.value.datetimeValue !== '请选择') {
    popup.value.open('bottom')
  }
}

const confirm = (obj) => {
  bukaData.value.datetimeValue = dayjs(obj.value).format('YYYY-MM-DD ')
}
const confirm1 = (obj) => {
  bukaData.value.bukashijian =
    dayjs(bukaData.value.datetimeValue).format('YYYY-MM-DD') +
    ':' +
    obj.value[1] +
    ':' +
    obj.value[2]
  console.log(bukaData.value.bukashijian, 'dsadsa')
}

const optionHistory = (item) => {
  popup.value.close()
  bukaData.value.bukabanci = item.punchType
  switch (item.punchType) {
    case '上午上班':
      if (item.punchTime) {
        bukaData.value.bukashijian = new dayjs(item.punchTime).format('YYYY-MM-DD HH:mm')
        pickerDefaultTime.value = [
          [new dayjs(bukaData.value.datetimeValue).format('YYYY-MM-DD')],
          [new dayjs(item.punchTime).format('HH')],
          [new dayjs(item.punchTime).format('mm')],
        ]
      } else {
        bukaData.value.bukashijian = new dayjs(bukaData.value.datetimeValue).format(
          'YYYY-MM-DD 08:00',
        )
        pickerDefaultTime.value = [
          [new dayjs(bukaData.value.datetimeValue).format('YYYY-MM-DD')],
          ['08'],
          ['00'],
        ]
      }
      break
    case '上午下班':
      if (item.punchTime) {
        bukaData.value.bukashijian = new dayjs(item.punchTime).format('YYYY-MM-DD HH:mm')
        pickerDefaultTime.value = [
          [new dayjs(bukaData.value.datetimeValue).format('YYYY-MM-DD')],
          [new dayjs(item.punchTime).format('HH')],
          [new dayjs(item.punchTime).format('mm')],
        ]
      } else {
        bukaData.value.bukashijian = new dayjs(bukaData.value.datetimeValue).format(
          'YYYY-MM-DD 12:00',
        )
        pickerDefaultTime.value = [
          [new dayjs(bukaData.value.datetimeValue).format('YYYY-MM-DD')],
          ['12'],
          ['00'],
        ]
      }
      break
    case '下午上班':
      if (item.punchTime) {
        bukaData.value.bukashijian = new dayjs(item.punchTime).format('YYYY-MM-DD HH:mm')
        pickerDefaultTime.value = [
          [new dayjs(bukaData.value.datetimeValue).format('YYYY-MM-DD')],
          [new dayjs(item.punchTime).format('HH')],
          [new dayjs(item.punchTime).format('mm')],
        ]
      } else {
        bukaData.value.bukashijian = new dayjs(bukaData.value.datetimeValue).format(
          'YYYY-MM-DD 02:00',
        )
        pickerDefaultTime.value = [
          [new dayjs(bukaData.value.datetimeValue).format('YYYY-MM-DD')],
          ['02'],
          ['00'],
        ]
      }

      break
    case '下午下班':
      if (item.punchTime) {
        bukaData.value.bukashijian = new dayjs(item.punchTime).format('YYYY-MM-DD HH:mm')
        bukaData.value.bukashijian = [
          [new dayjs(bukaData.value.datetimeValue).format('YYYY-MM-DD')],
          [new dayjs(item.punchTime).format('HH')],
          [new dayjs(item.punchTime).format('mm')],
        ]
        pickerDefaultTime.value = [
          [new dayjs(bukaData.value.datetimeValue).format('YYYY-MM-DD')],
          [new dayjs(item.punchTime).format('HH')],
          [new dayjs(item.punchTime).format('mm')],
        ]
      } else {
        bukaData.value.bukashijian = new dayjs(bukaData.value.datetimeValue).format(
          'YYYY-MM-DD 18:00',
        )
        pickerDefaultTime.value = [
          [new dayjs(bukaData.value.datetimeValue).format('YYYY-MM-DD')],
          ['18'],
          ['00'],
        ]
      }
      break
  }
}
const formatter = (type, value) => {
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  if (type === 'hour') {
    return `${value}时`
  }
  if (type === 'minute') {
    return `${value}分`
  }
  return value
}

const deptId = ref(null)
const userId = ref(null)
let attchment = ref(null)

const getDesignDrawingsEmit = (emit) => {
  attchment.value = emit
}

const clickSave = async () => {
	if(isObjectValuesNotEmpty(bukaData.value)){
		let params = {
		  deptId: deptId.value,
		  userId: userId.value,
		  date: dayjs(bukaData.value.bukashijian).format('YYYY-MM-DD HH:mm:ss'),
		  position: bukaData.value.bukabanci,
		  reason: bukaData.value.bakahsiyou,
		  attchment: JSON.stringify(attchment.value),
		  type: '补卡',
		  ruleId: 'buka',
		  approve: approvalProcessState.state.approvalProcess,
		}
		let { code } = await attendanceApplyApi(params)
		if (code === 200) {
		  uni.showToast({
		    title: '提交成功',
		    duration: 1500,
		    icon: 'success',
		  })
		
		  setTimeout(() => {
		    uni.navigateBack({
		      url: '/pages/attendance/attendancePage',
		    })
		  }, 1000)
		}
	}else{
		uni.showToast({
			title:'请输入完整数据',
			icon:'error'
		})
	}
   
}

const getUserProfileFn = async () => {
  let { code, data } = await getUserProfile()
  if (code === 200) {
    deptId.value = data.deptId
    userId.value = data.userId
  }
}

watch(
  () => bukaData.value.datetimeValue,
  (val) => {
    console.log(val)
    bukaData.value = {
      datetimeValue: val,
      bukabanci: '请选择',
      bukashijian: '请选择',
      bakahsiyou: '',
    }
    columns.value[0][0] = val
    pickerDefaultTime.value[0][0] = val
    // 历史 打卡记录
    const params = {
      userId: userId.value,
      deptId: deptId.value,
      punchTimeLte: new dayjs(val).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      punchTimeGte: new dayjs(val).endOf('day').format('YYYY-MM-DD HH:mm:ss'),
    }

    const obj = ref([
      {
        punchType: '上午上班',
        type: '缺卡',
        punchTime: null,
      },
      {
        punchType: '上午下班',
        type: '缺卡',
        punchTime: null,
      },
      {
        punchType: '下午上班',
        type: '缺卡',
        punchTime: null,
      },
      {
        punchType: '下午下班',
        type: '缺卡',
        punchTime: null,
      },
    ])
    let indexs = []
    getAttendanceRecordList(params).then((item) => {
      obj.value.forEach((v, i) => {
        if ( dayjs().isBefore(dayjs(val + ' 8:00'))) {
          if (v.punchType === '上午上班') {
            indexs.push(i)
          }
        }
        if ( dayjs().isBefore(dayjs(val + ' 12:00'))) {
          if (v.punchType === '上午下班') {
            indexs.push(i)
          }
        }
        if ( dayjs().isBefore(dayjs(val + ' 14:00'))) {
          if (v.punchType === '下午上班') {
            indexs.push(i)
          }
        }
        if ( dayjs().isBefore(dayjs(val + ' 18:00'))) {
          if (v.punchType === '下午下班') {
            indexs.push(i)
          }
        }
        item.rows.forEach((v1, i1) => {
          if (v.punchType === v1.punchType) {
            obj.value[i] = v1
          }
        })
      })
      listTime.value = obj.value.filter((value, index) => !indexs.includes(index))
    })
  },
)
onLoad(async () => {
  await getUserProfileFn()
})
</script>

<style lang="scss" scoped>
@import '@/static/style/index.scss';

.bukaSvg {
  width: 32rpx;
  height: 32rpx;
}

.buttonContainer {
  position: fixed;
  bottom: 0;
  display: flex;
  justify-content: center;
  width: 100%;
  align-items: center;
  padding: 16rpx;
  background-color: #fff;
}

.buttonClass {
  display: flex;
  width: 686rpx;
  height: 72rpx;
  justify-content: center;
  align-items: center;
  background: #165dff;
  border-radius: 16rpx;
  color: #fff;
  font-size: 32rpx;
  //margin-top: 40rpx;
  overflow: hidden;
}

.blank {
  height: calc(72rpx + 32rpx + 20rpx);
}

.bukabanci {
  .info-content {
    color: #86909c !important;
  }

  .info-list-left {
    // @include font-color-auxiliary;
    color: #86909c !important;
  }
}

.textarea-box {
  background: #fff;
  padding: 20rpx;
  margin-top: 20rpx;

  .info-list-left {
    // @include font-color-auxiliary;
    color: #1d2129;
    font-size: $font-size-base;
  }

  .textinfo-list {
    margin-top: 20rpx;
    width: 100%;
    height: 200rpx;
  }
}

.popup-content {
  background: #f7f8fa;

  .header-box {
    padding: 30rpx 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    p {
      color: #1d2129;
      font-size: 34rpx;
      font-weight: 500;
    }

    .module-image-ba {
      border-radius: 32rpx;
      background: #f2f3f5;
      width: 45rpx;
      height: 45rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      image {
        width: 32rpx;
        height: 32rpx;
      }
    }
  }

  .card-list {
    display: flex;
    align-items: center;
    flex-direction: column;
    padding: 20rpx 30rpx;
    box-sizing: border-box;

    .list {
      box-shadow: 0 4rpx 16rpx 0 #0000000d;
      box-sizing: border-box;
      width: 100%;
      background: #fff;
      padding: 16rpx 24rpx;
      border-radius: 8rpx;
      margin-bottom: 10rpx;

      h4 {
        display: flex;
        color: #1d2129;
        font-size: 32rpx;
        font-weight: 400;
      }

      p {
        color: #86909c;
        font-size: 24rpx;
        font-weight: 400;
        margin-top: 10rpx;
      }
    }
  }
}

.measurement-info-list {
  @include flex($align: center, $justify: space-between);
  padding: $spacing-row-base;
  background: #fff;
  margin-top: 16rpx;

  .info-list-left {
    // @include font-color-auxiliary;
    color: #1d2129;
    font-size: $font-size-base;
  }

  .info-list-right {
    @include flex($align: center);

    .info-content {
      @include textStyleBase;
      font-size: 34rpx;
    }

    .iconfont {
      margin-left: 16rpx;
      // @include font-color-auxiliary;
      color: $uni-fc-fu-lin;
    }
  }

  .unit {
    // @include font-color-auxiliary;
    color: $uni-fc-fu-lin;
  }
}
</style>
